import java.util.*;

/**
 * @author LKQ
 * @date 2022/5/21 9:33
 * @description 排序 + 贪心
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] tokens = {100,200,300,400};
        solution.bagOfTokensScore(tokens, 200);
    }
    public int bagOfTokensScore(int[] tokens, int P) {
        Arrays.sort(tokens);
        int lo = 0, hi = tokens.length - 1;
        int points = 0, ans = 0;
        while (lo <= hi && (P >= tokens[lo] || points > 0)) {
            // 能量够，就一直翻能量最小的令牌，得分
            while (lo <= hi && P >= tokens[lo]) {
                P -= tokens[lo++];
                points++;
            }

            ans = Math.max(ans, points);
            if (lo <= hi && points > 0) {
                // 只置换一次最大的能量
                P += tokens[hi--];
                points--;
            }
        }
        return ans;
    }
}
